import storage_manager
from datetime import datetime, timedelta
EVENT_TYPES = ["讲座", "活动", "考试", "DDL", "其他"]

def get_event_details_input():
    name = input("请输入事件名称：")
    date = input("请输入日期 (格式 YYYY-MM-DD)：")
    while not validate_date(date):
        print("日期格式错误，请重新输入！")
        date = input("请输入日期 (格式 YYYY-MM-DD)：")
    time = input("请输入时间 (可选, 格式 HH:MM)：")
    if time and not validate_time(time):
        print("时间格式错误，时间将被设置为空！")
        time = ""
    event_type = input(f"请输入事件类型 ({', '.join(EVENT_TYPES)})：")
    while event_type not in EVENT_TYPES:
        print("事件类型无效，请重新输入！")
        event_type = input(f"请输入事件类型 ({', '.join(EVENT_TYPES)})：")
    description = input("请输入事件描述 (可选)：")
    event_id = generate_unique_event_id()
    return {
        "event_id": event_id,
        "name": name,
        "date": date,
        "time": time,
        "type": event_type,
        "description": description
    }

def validate_date(date):
    try:
        datetime.strptime(date, "%Y-%m-%d")
        return True
    except ValueError:
        return False

def validate_time(time):
    try:
        datetime.strptime(time, "%H:%M")
        return True
    except ValueError:
        return False

def generate_unique_event_id():
    return str(int(datetime.now().timestamp()))

def add_new_event_interaction():
    return get_event_details_input()

def format_event_for_display(event_dict, show_id_and_index=False, index=None):
    event_text = f"名称：{event_dict['name']}\n"
    event_text += f"日期：{event_dict['date']}\n"
    event_text += f"时间：{event_dict['time'] if event_dict['time'] else '无'}\n"
    event_text += f"类型：{event_dict['type']}\n"
    event_text += f"描述：{event_dict['description'] if event_dict['description'] else '无'}\n"
    if show_id_and_index:
        event_text = f"{index}. {event_text}"
    return event_text

def filter_events_by_date(target_date_str, all_events):
    return [event for event in all_events if event["date"] == target_date_str]

def view_events_for_specific_date_interaction(for_deletion=False):
    date = input("请输入日期 (格式 YYYY-MM-DD)：")
    if not validate_date(date):
        print("日期格式错误！")
        return
    all_events = storage_manager.load_all_events_from_file()
    events_on_date = filter_events_by_date(date, all_events)
    if events_on_date:
        print(f"\n{date} 的事件列表：")
        for i, event in enumerate(events_on_date, start=1):
            print(format_event_for_display(event, show_id_and_index=for_deletion, index=i))
    else:
        print("该日期没有事件！")
    return events_on_date

def filter_upcoming_events(all_events, days_limit=7):
    today = datetime.today()
    future_date = today + timedelta(days=days_limit)
    return [event for event in all_events if today <= datetime.strptime(event["date"], "%Y-%m-%d") <= future_date]

def view_upcoming_events_interaction():
    days = input("请输入天数N（默认为7天）：")
    if days == "":
        days = 7
    else:
        days = int(days)
    all_events = storage_manager.load_all_events_from_file()
    upcoming_events = filter_upcoming_events(all_events, days)
    if upcoming_events:
        print(f"\n从今天起未来{days}天内的事件列表：")
        for event in upcoming_events:
            print(format_event_for_display(event))
    else:
        print("未来几天内没有事件！")

def delete_event_interaction():
    events_on_date = view_events_for_specific_date_interaction(for_deletion=True)
    if not events_on_date:
        return storage_manager.load_all_events_from_file()
    try:
        choice = int(input("请输入要删除的事件序号："))
        if 1 <= choice <= len(events_on_date):
            event_to_delete = events_on_date[choice - 1]
            all_events = storage_manager.load_all_events_from_file()
            all_events = [event for event in all_events if event["event_id"] != event_to_delete["event_id"]]
            print("事件已删除！")
            return all_events
        else:
            print("无效的序号！")
    except ValueError:
        print("输入格式错误，请输入有效的数字！")
    return storage_manager.load_all_events_from_file()